<template>
<Transition>
  <div class="tree_box" :class="{close:showTree}" v-if="isShow" @mouseover="showClose = true" @mouseleave="showClose = false">
    <el-input v-if="!showTree" v-model="searchWord" placeholder="模糊搜索" style="width:260px;margin:0 0 12px 0;" prefix-icon="Search"></el-input>
    <el-tree v-if="!showTree" ref="treeRef" class="filter-tree" :data="treeData"
      :filter-node-method="filterNode" @node-click="handleNodeClick" node-key="id">
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span class="iconfont" v-if="data.children?.length != 0 && !node.expanded">
            <img class="image" src="@/assets/images/nav/文件夹1.png" alt="">
          </span>
          <span class="iconfont" v-if="data.children?.length != 0 && node.expanded">
            <img class="image" src="@/assets/images/nav/文件夹.png" alt="">
          </span>
          <span class="iconfont" v-if="data.children?.length == 0">
            <img class="image" src="@/assets/images/nav/表格.png" alt="">
          </span>
          <span :title="node.label">{{ formatTreeFn(node.label) }}</span>
        </span>
      </template>
    </el-tree>
    <!-- v-if="showClose" -->
    <div class="btn" :class="{left:showTree}" v-if="showClose">
      <el-icon v-if="!showTree" @click="closeTree"><ArrowLeftBold /></el-icon>
    </div>
    <div class="btn" :class="{left:showTree}" v-if="showTree">
      <el-icon v-if="showTree" @click="closeTree"><ArrowRightBold /></el-icon>
    </div>
  </div>
</Transition>
</template>
<script setup>
import usePermissionStore from '@/store/modules/permission'
import useSettingsStore from '@/store/modules/settings'
import { onMounted } from 'vue';
import { useRouter } from "vue-router";

const router = useRouter();
const settingsStore = useSettingsStore()
const permissionStore = usePermissionStore()
const routers = computed(() => permissionStore.topbarRouters);
console.log(routers);

let treeRef = ref()
const treeData = ref([])
const path = computed(() => settingsStore.routerName);
const isShow = computed(() => settingsStore.isShow);
const treeArr = ref([])
const searchWord = ref('')
const showClose = ref(false)
const showTree = ref(false)

const setTreeData1 = (p) => {
  console.log(p);
  treeArr.value = []
    routers.value.forEach(item => {
        if(item.path.includes(p) && !item.hidden){
            if(item.children){
                treeArr.value = item.children
            }
        }
    });
}
// setTreeData1(path.value)
const setTreeData2 = () => {
  let arr = treeArr.value.map((item) => {
    return { label: item.meta.title, id: item.path,expanded:false,parentId:''}
  })
  let dataList = treeArr.value
  let findItemByLabel = (arr, dataList) => {//递归
    arr.forEach(item2 => {
      dataList.forEach(item3 => {
        if (item2.label == item3.meta.title) {
          item2.children = item3.children?item3.children:[]
          if (item2.children?.length > 0) {
            let arr2 = []
            arr2 = item2.children.map((item4) => {
              return { label: item4.meta.title, id: item4.path,expanded:false,parentId:item2.id }
            })
            const foundInChildren = findItemByLabel(arr2, item3.children);
            if (foundInChildren) {
              foundInChildren.forEach(itm => {
                if (!itm.children) {
                  itm.children = []
                }
              })
              item2.children = foundInChildren
            }
            return foundInChildren;
          }
        }
      })
    })
    return arr
  };
  treeData.value = findItemByLabel(arr,dataList)
  if(treeData.value.length != 0){
    if(treeData.value[0].children.length == 0){
      settingsStore.path = '/' + path.value + '/' + treeData.value[0].id
    }else{
      settingsStore.path = '/' + path.value + '/' + treeData.value[0].children.id
    }
  }
}
// setTreeData2()
function formatTreeFn(val) {
  if (val.length > 8) {
    return val = val.slice(0, 8) + '...';
  } else {
    return val
  }
}


const handleNodeClick = (node) => {
  node.expanded = !node.expanded
  if(node.children?.length == 0){
    let str = path.value
    let arr = []
    let setRouter = (node) =>{
      arr.push(node.id)
      if(node.parentId != ''){
        let obj = treeRef.value.getNode(node.parentId).data
        setRouter(obj)
      }
      return arr
    }
    let arr2 = setRouter(node).slice().reverse()
    console.log(arr2);
    console.log(arr2.join('/'));
    if(arr2.join('/').includes(str)){
      router.push(`${arr2.join('/')}`)
    }else{
      str += '/' + arr2.join('/')
      router.push(`/${str}`)
    }
  }
}
const filterNode = (value, data) => {
  // console.log(value, 'value')
  if (!value) return true
  return data.label.includes(value)
}
const closeTree = () =>{
  // settingsStore.routerName = ''
  if(showTree.value){
    document.querySelector(':root').style.setProperty('--base-width','calc(100% - 280px)');
  }else{
    document.querySelector(':root').style.setProperty('--base-width','100%');
  }
    showTree.value = !showTree.value
}

//树形
watch(() => searchWord.value, (val) => {
  // console.log(proxy.$refs['treeRef'])
  treeRef.value.filter(val)
})
watch(() => path.value, (val) => {
  console.log(val);
  if(val != ''){
    setTreeData1(path.value)
    setTreeData2()
  }
})
onMounted(()=>{
  if(path.value != ''){
    setTreeData1(path.value)
    setTreeData2()
  }
})

</script>
<style lang="scss" scoped>
.tree_box{
  padding: 10px;
  width: 280px;
  background-color: #fff;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  transition: width 0.3s ease;
}

.custom-tree-node{
  display: flex;
  align-items: center;
  .iconfont{
    margin: 0 3px 0 0;
    width: 16px;
    height: 16px;
  }
}

.close{
  width: 25px !important;
}
.left{
  left: 0px !important;
}


.btn{
  position: absolute;
  left: 255px;
  top: 50%;
  width: 24px;
  height: 24px;
  background-color: #409eff;
  border-radius: 50%;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  z-index: 999;
}
.btn:hover{
  cursor: pointer;
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>
